package com.uzhie.web.service;

import com.uzhie.web.bean.PageBean;
import com.uzhie.web.dao.CatalogDAO;
import com.uzhie.web.dao.UserCatalogDAO;
import com.uzhie.web.dao.UserDAO;
import com.uzhie.exception.CatalogException;
import com.uzhie.exception.MonitorException;
import com.uzhie.exception.UserException;
import com.uzhie.jt808.service.JT808ServiceImpl;
import com.uzhie.web.module.User;
import com.uzhie.web.module.UserCatalog;
import com.uzhie.util.ConstantKit;
import com.uzhie.web.module.Catalog;
import com.uzhie.util.TreeBuildUtil;
import com.uzhie.util.TreeUtil;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;

/**
 * 用户service,封装与用户相关的服务操作
 * <p>
 * Created by zhangdequan on 2018/7/12.
 */
@Service
public class CatalogService {

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private CatalogDAO catalogDAO;
    @Autowired
    private UserCatalogDAO userCatalogDAO;
    @Autowired(required = false)
    private JT808ServiceImpl jt808Service;

    /**
     * 查询返回所有的目录数据
     *
     * @return
     */
    public List<Catalog> selectAllCatalogList(String parentId, PageBean pageBean) {
        List<Catalog> list = catalogDAO.selectAllCatalog(parentId, pageBean.getRowBounds());
        return list;
    }

    /**
     * 查询返回所有的目录数据(树状结构)
     *
     * @return
     */
    public List<Catalog> selectAllCatalogToTree() {
        List<Catalog> list = catalogDAO.selectAllCatalogToTree();
        return new TreeUtil(list).buildTree();
    }

    /**
     * 添加目录对象
     *
     * @param catalog 目录对象
     * @throws CatalogException
     */
    public void addCatalog(@NotNull(message = CatalogException.Status.CATALOG_ISNULL) @Valid Catalog catalog) throws CatalogException {
        //更新时间
        catalog.setCreateTime(new Date());
        catalog.setStatus(ConstantKit.STATUS.IS_AVAILABLE);
        int t = catalogDAO.insert(catalog);
        if (t != 1) throw new CatalogException(CatalogException.Status.INSERT_ERROR);
        if (catalog.getCreateId() != null) {
            UserCatalog userCatalog = new UserCatalog();
            userCatalog.setCatalogId(catalog.getId());
            userCatalog.setCatalogName(catalog.getName());
            userCatalog.setUserId(catalog.getCreateId());
            userCatalog.setUserName(catalog.getCreateName());
            userCatalogDAO.insert(userCatalog);
        }

    }

    /**
     * 查询所有的菜单树
     * create by lilongfei
     *
     * @return
     */
    public List<Catalog> selectCatalogToBinding() {
        List<Catalog> result = null;
        try {
            result = catalogDAO.selectAllCatalogtoBinding();
            result = new TreeUtil(result).buildTree();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return result;
        }
    }

    /**
     * 通过部门id查询所有子节点的目录 非管理功能
     *
     * @param catalogId
     * @return
     */
    public List<Catalog> selectCatalogByDepart(@NotEmpty(message = CatalogException.Status.CATALOG_ID_ISNULL) String catalogId) {
        List<Catalog> result = null;
        try {
            result = catalogDAO.selectCatalogByUserDepart(catalogId);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return result;
        }
    }

    /**
     * 通过部门id查询所有子节点的目录,管理功能
     *
     * @param catalogId
     * @return
     */
    public List<Catalog> selectCatalogByDepartForAdmin(@NotEmpty(message = CatalogException.Status.CATALOG_ID_ISNULL) String catalogId) {
        List<Catalog> result = null;
        try {
            result = catalogDAO.selectCatalogByUserDepartForAdmin(catalogId);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return result;
        }
    }


    /**
     * 通过部门id,获取所有子节点信息
     *
     * @param catalogId
     */
    public List<Catalog> selectCatalogByDepartToTree(@NotEmpty(message = CatalogException.Status.CATALOG_ID_ISNULL) String catalogId) {
        List<Catalog> result = null;
        try {
            result = catalogDAO.selectCatalogByUserDepart(catalogId);
            result = new TreeUtil(result).buildTreeByTop();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return result;
        }
    }

    /**
     * 查询目录详情
     *
     * @param catalogId 目录id
     * @return
     */
    public Catalog selectCatalogById(String catalogId) {
        return catalogDAO.selectCatalogById(catalogId);
    }

    /**
     * 根据人员信息查询树状目录结构(前端树状显示)
     *
     * @param userId
     * @return
     */
    public List<Catalog> selectCatalogByUserId(String userId) {
        return catalogDAO.selectCatalogByUserId(userId);
    }

    /**
     * 返回所有车辆数据,包含车辆目录节点,在用户绑定车辆关系时使用, 只查询了车辆名称和id属性
     * created by lilongfei
     *
     * @return
     **/
    public List<Catalog> selectAllCatalogAndCar(@NotEmpty(message = UserException.Status.ID_ISNULL) String userId) throws MonitorException {
        User user = userDAO.selectByPrimaryKey(userId);
        if (user == null) throw new MonitorException(MonitorException.Status.USER_ERROR);
        //用户关联的权限目录
        List<Catalog> nodes = catalogDAO.selectCatalogByUserId(userId);
        //通过部门id全部的权限目录
        List<Catalog> origins = catalogDAO.selectCatalogByUserDepart(user.getDepartmentId());
        if (nodes != null && nodes.size() > 0) {
            //迭代出用户关联的权限目录的全部上级目录
            List<Catalog> result = new TreeBuildUtil(origins, nodes).filter();
            //通过目录list构建目录树
            result = new TreeUtil(result, jt808Service).buildCatalogTreeNoCha();
            return result;
        } else
            throw new MonitorException(MonitorException.Status.NODE_ERROR);
    }

    /**
     * 通过用户关联的管理权限，查询可管理的部门
     *
     * @param userId
     * @return
     * @throws MonitorException
     */
    public List<Catalog> selectCatalogByUserPower(@NotEmpty(message = CatalogException.Status.CATALOG_ID_ISNULL) String userId) throws MonitorException {
        User user = userDAO.selectByPrimaryKey(userId);
        if (user == null) throw new MonitorException(MonitorException.Status.USER_ERROR);
        //用户关联的权限目录
        List<Catalog> nodes = catalogDAO.selectCatalogByUserIdNoCar(userId);
        //通过部门id全部的权限目录
        List<Catalog> origins = catalogDAO.selectCatalogByUserDepart(user.getDepartmentId());
        if (nodes != null && nodes.size() > 0) {
            //迭代出用户关联的权限目录的全部上级目录
            List<Catalog> result = new TreeBuildUtil(origins, nodes).filter();
            //通过目录list构建目录树
            result = new TreeUtil(result, jt808Service).buildTreeByTop();
            return result;
        } else
            throw new MonitorException(MonitorException.Status.NODE_ERROR);
    }


    /**
     * 编辑目录对象
     *
     * @param catalog
     * @throws CatalogException
     */
    public void updateCatalog(Catalog catalog) throws CatalogException {
        //更新时间
        catalog.setUpdateTime(new Date());
        switch (catalog.getStatus()) {
            case 0:
            case 2:
                //判断当前目录是否被引用，判断依据为：部门id没有被车辆引用，没有被设备引用，没有被人员引用，该目录下不存在子目录，视为目录没有被引用
                Integer count = catalogDAO.catalogHasBeUsed(catalog.getId());
                if (null != count && count > 0) {
                    //count >0 证明该目录已被引用，需要先处理引用数据后才可以对目录执行禁用或删除动作
                    throw new CatalogException(CatalogException.Status.CATALOG_HAS_BE_USED);
                }
                //删除目录
                if (catalog.getStatus() == 0) {
                    catalogDAO.deleteByPrimaryKey(catalog.getId());
                    break;
                }
            case 1:
                //禁用或启用目录
                int t = catalogDAO.updateByPrimaryKeySelective(catalog);
                if (t != 1) throw new CatalogException(CatalogException.Status.UPDATA_ERROR);
                break;
            default:
                throw new CatalogException(CatalogException.Status.UPDATA_STATUS_ERROR);
        }
    }

    /**
     * 根据目录id,批量更新目录状态信息
     *
     * @param catalogIds id集合
     * @param status     状态
     * @return
     */
    public void updateCatalogStatusById(List<Catalog> catalogIds, Integer status) throws CatalogException {
        if (catalogIds.size() == 0) throw new CatalogException(CatalogException.Status.ID_ISNULL);
        for (Catalog catalog : catalogIds) {
            catalog.setUpdateTime(new Date());
            switch (status) {
                case 0:
                case 2:
                    //判断当前目录是否被引用，判断依据为：部门id没有被车辆引用，没有被设备引用，没有被人员引用，该目录下不存在子目录，视为目录没有被引用
                    Integer count = catalogDAO.catalogHasBeUsed(catalog.getId());
                    if (null != count && count > 0) {
                        //count >0 证明该目录已被引用，需要先处理引用数据后才可以对目录执行禁用或删除动作
                        throw new CatalogException(CatalogException.Status.CATALOG_HAS_BE_USED);
                    }
                    //删除目录
                    if (status == 0) {
                        catalogDAO.deleteByPrimaryKey(catalog);
                        break;
                    }
                case 1:
                    int t = catalogDAO.updateCatalogStatusById(catalog.getId(), status);
                    if (t == 0) throw new CatalogException(CatalogException.Status.UPDATA_STATUS_ERROR);
                    break;
                default:
                    throw new CatalogException(CatalogException.Status.UPDATA_STATUS_ERROR);

            }
        }
    }


}


